package common

import (
	"livefind/common"
	"livefind/common/request"
	"livefind/utils"
)

const defaultSortField = "createTime"

func ParseQueryRule(r interface{}) (q common.Query) {
	pageInfo := request.PageInfo{}
	utils.StructAssign(&pageInfo, r)
	if pageInfo.PageSize <= 0 {
		q.Limit = 10
	} else {
		q.Limit = pageInfo.PageSize
	}

	if pageInfo.Page <= 1 {
		q.Skip = 0
	} else {
		q.Skip = (pageInfo.Page - 1) * q.Limit
	}

	if pageInfo.SortField == "" {
		q.SortField = defaultSortField
	} else {
		q.SortField = pageInfo.SortField
	}
	if !utils.InArray(pageInfo.SortRule, []interface{}{1, -1}) {
		q.SortRule = -1
	} else {
		q.SortRule = pageInfo.SortRule
	}

	return q
}
